<template>
  <div class="content">
    <card title="用户管理" size="large">
      <el-button plain :icon="RefreshRight" size="default" @click="reset()">重置</el-button>
      <template #main>
        <el-row>
          <el-col :span="16">
            <div class="form-item">
              <span>用户名</span>
              <el-input 
                v-model.trim="queryData.name" 
                placeholder="请输入用户名"
                clearable
                style="max-width: 500px;"
                @keyup.enter.native="search()"
                @change="search()">
              </el-input>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="btn-item">
              <el-button type="primary" size="default" plain :icon="Search" @click="search()">
                搜索
              </el-button>
            </div>
          </el-col>
        </el-row>
      </template>
    </card>
    <div class="card-content">
      <div class="oper-box">
        <el-button type="primary" size="default" :icon="Plus" @click="handleCreate()">新增</el-button>
        <el-button type="primary" size="default" :icon="Delete" @click="handleBatchDelete" v-show="globalStore.deleteAuthority">批量删除</el-button>
        <el-button type="primary" size="default" :icon="Download" plain @click="handleDownload()">导出</el-button>
      </div>
      <el-table
        :data="tableData"
        ref="multipleTableRef"
        v-loading="loading"
        row-key="id"
        size="default"
        empty-text="暂无数据"
        highlight-current-row
        class="primary-table"
        @selection-change="handleSelect"
        @select-all="handleSelectAll">
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column prop="nickname" label="昵称" min-width="100" show-overflow-tooltip fixed="left"></el-table-column>
        <el-table-column prop="realname" label="真名" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="age" label="年龄" min-width="80" show-overflow-tooltip></el-table-column>
        <el-table-column prop="gender" label="性别" min-width="80" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.gender === 0 ? '暂不清楚' : row.gender === 1 ? '女' : '男' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" min-width="120" label="手机号" show-overflow-tooltip>
          <template #default="{ row }">
            <!-- {{ row.maritalStatus === 0 ? '单身' : row.maritalStatus === 1 ? '有对象':row.maritalStatus === 2 ? '已婚' : '离异' }} -->
            {{ row.phone }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" min-width="100" show-overflow-tooltip fixed="left"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" min-width="170" sortable show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.create_time ? row.create_time.slice(0,10):'' }}
          </template>
        </el-table-column>
        <el-table-column prop="introduction" label="自我介绍" min-width="120" show-overflow-tooltip ></el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
                <el-button 
                    link 
                    type="primary" 
                    :icon="View" 
                    @click="openUserDetail(scope.row.user_id)">
                </el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top">
                <el-button 
                    link 
                    type="primary" 
                    :icon="Edit" 
                    @click="handleEdit(scope.$index, scope.row)">
                </el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
                <el-button 
                    link 
                    type="primary" 
                    :icon="Delete" 
                    @click="handleDelete(scope.$index, scope.row)" 
                    v-show="globalStore.deleteAuthority">
                </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:page-size="queryData.pageSize"
        :current-page="queryData.pageNum"
        background
        layout="total, prev, pager, next"
        :total="total"
        :page-sizes="[10, 20, 30, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </div>
  <!-- <editItem :data="itemData" :showItem="showItem" @closeItem="closeItem"></editItem> -->
  <el-dialog
      v-if="dialogEdit"
      v-model="dialogEdit" 
      :title="currentUserId ? '编辑用户' : '新增用户'" 
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="log-dialog"
      @before-close="closeEdit">
      <addOrEdit :id="currentUserId || ''" @back="closeEdit"></addOrEdit>
  </el-dialog>
  <el-dialog
      v-if="dialogUser"
      v-model="dialogUser" 
      title="用户详情" 
      append-to-body
      destroy-on-close
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="log-dialog"
      @before-close="closeUserDetail">
      <userDetails :id="currentUserId || ''"></userDetails>
  </el-dialog>
</template>

<script setup lang="ts">
// import { Search } from '@element-plus/icons-vue'
import { ref,onMounted } from 'vue'
import addOrEdit from './components/addOrEdit.vue'
import card from '../../components/card/index.vue'
import userDetails from './components/userDetails.vue'
import { Delete, Edit, Search, Plus, RefreshRight, Download, View } from '@element-plus/icons-vue'
import { getUserByPageNicknameSort,deleteUserById,deleteUserAmount } from '../../api/user'
import { ElMessage,ElMessageBox } from 'element-plus'
import { handleExport } from '../../excel/export'
import useGlobalStore from '../../store/modules/global';

const globalStore = useGlobalStore()
//搜索
// const searchInput = ref('')
const queryData = ref({
  name: '',
  pageSize: 10,
  pageNum: 1,
  sortOrder:'DESC',
  sortFieldName:'create_time'
})

// const itemData = ref({})
// const showItem = ref(false)
const total = ref(0)
const loading = ref(false)
const multipleSelection = ref([])

let currentUserId = ref('')
let dialogUser = ref(false)
let dialogEdit = ref(false)

//新增
const handleCreate = () =>{
  dialogEdit.value = true
}

// interface tableDataInterface {
//   id: number,
//   nickname: string,
//   relname: string,
//   age: number,
//   gender: number, // 0为女，1为男
//   // maritalStatus: number, // 婚姻状态 0为单身 1为有对象 2为已婚 3为离异
//   phone:String,//手机号
//   registrationtime: string, //注册时间
//   // member: boolean, // 是否为会员
//   introduction: string //自我介绍
// }
//表格部分
const tableData= ref([])

//表格右侧部分操作里面的编辑
const handleEdit = (index: any, row: any) => {
  console.log('index: ', index);
  currentUserId.value = row.user_id
  dialogEdit.value = true
}
const closeEdit = () => {
  search()
  dialogEdit.value = false
  currentUserId.value = ''
}
const handleDelete = async(index: any, row: any) => {
  console.log('index: ', index);
  ElMessageBox.confirm(`确认删除'${row.nickname}'？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async () => {
        // 调删除接口
        const result = await deleteUserById({
          user_id:row.user_id
        })
        //@ts-ignore
        if(result.code == 1){
          ElMessage({
              message: '删除成功',
              type: 'success',
          })
          search()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消删除！',
            showClose: true
        })
    })
 
}
// 打开用户详情
const openUserDetail = (id: Number) => {
  //@ts-ignore
    currentUserId.value = id
    dialogUser.value = true
}
// 关闭用户详情
const closeUserDetail = () => {
    currentUserId.value = ''
    dialogUser.value = false
}
// 搜索
const search = async() => {
  tableData.value = []
  const result = await getUserByPageNicknameSort(queryData.value)
  tableData.value = result.data
  //@ts-ignore
  total.value = result.total
}
// 重置
const reset = () => {
  queryData.value.name = ''
  queryData.value.pageNum = 1,
  queryData.value.pageSize = 20
  search()
}
const handleSizeChange = (size: number) => {
  queryData.value.pageSize = size
  // queryData.value.pageNum = 1
  search()
}

const handleCurrentChange = (page: number) => {
  queryData.value.pageNum = page
  search()
}
//批量删除
const handleBatchDelete = async() => {
  if (!multipleSelection.value.length) {
        ElMessage({
            type: 'warning',
            message: '请先选择用户！',
            showClose: true
        })
        return
    }
    ElMessageBox.confirm('确认删除选中的用户？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(async() => {
        // 调批量删除接口
        const result = await deleteUserAmount({
            users:multipleSelection.value
        })
        //@ts-ignore
        if (result.code == 1) {
            ElMessage({
                type: 'success',
                message: '删除成功',
                showClose: true
            })
            search()
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '已取消批量删除！',
            showClose: true
        })
    })
}

const handleSelect = (selection: Object) => {
  //@ts-ignore
  multipleSelection.value = selection
}
const handleSelectAll = (selection: Object) => {
  //@ts-ignore
  multipleSelection.value = selection
}
//导出
const handleDownload = () => {
  handleExport(tableData.value,'用户数据')
}
onMounted(() => {
  search()
})
</script> 

<style lang="less" scoped>
.search-all {
  background-color: #fff;
  padding: 12px;

  .el-input {
    width: 600px;
    height: 50px;
  }

  #search-btn1,
  #search-btn2 {
    height: 100%;
    background-color: #6383ff;
    color: #fff;
  }  .el-button {
    height: 50px
  }
}

.table-all {
  padding: 12px;
  background-color: #fff;
  .page{
    position: relative;
    height: 20px;
    .el-pagination{
      position: absolute;
      top:0;
      right: 0;
      height: 20px;
    }
  }
}
</style>
